package com.taptech.doufu.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.taptech.doufu.R;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.event.EventBusMyTag;
import com.taptech.doufu.net.retrofit.api.ApiClient;
import com.taptech.doufu.net.retrofit.api.BaseSubscriber;
import com.taptech.doufu.net.retrofit.api.RxJavaHelper;
import com.taptech.doufu.bean.TagBean;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.bean.TagRecommendGsonBean;
import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity;
import com.taptech.doufu.ui.view.personalcenter.TextTagsViewGroup;
import com.taptech.doufu.services.UGCMainService;
import com.taptech.doufu.ui.adapter.TagAapater;
import com.taptech.doufu.util.at.MyClickListenner;
import com.taptech.doufu.util.DiaobaoUtil;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.taptech.doufu.ui.view.WaitDialog;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AddTagTosActivity extends DiaobaoBaseActivity implements OnClickListener, HttpResponseListener
{

    public final static int MESSAGE_TAG_CLICK = 10001;
    public final static int MESSAGE_TAG_DELTE = 10002;
    public final static int MESSAGE_TAG_BACK = 10003;
    public  int TAG_SIZE = 5;
    private static final int TAG_HISTORY_SIZE_USER = 6;
    private static final int TAG_MAX_SIZE = 8;
    public static final String INTENT_KEY_SEXUALITY = "intent_sexuality";
    public static final String INTENT_KEY_THEME_KEY = "intent_theme_key";


    private TextTagsViewGroup tags_viewgroup;
    private TextView tags_num_tv, new_tag_tv,tvMakeSure;
    private EditText search_tag_et;
    private GridView tags_list;
    private TagAapater searchTAGAdapter;
    private LinearLayout tipLayout;
    private WaitDialog waitDialog;
    private Handler mhandler;
    private int type_from;
    private View hot_ly, latest_ly, search_ly;
    private GridView hot_gv, latest_gv;
    ArrayList<String> hotTagsList = new ArrayList<String>();
    ArrayList<String> searchTagsList = new ArrayList<String>();
    ArrayList<String> latestTagsList = new ArrayList<String>();
    ArrayList<String> tempTagsList = new ArrayList<String>();
    private View search_del;
    private String last = "";
    private View new_tag_ly;
    private int sexuality;
    private String themeKey; //题材
    private TextView tvTip;
    private ImageView ivBack;
    private int single_page;


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        addShadeBg();
        setContentView(R.layout.activity_add_tag_tos);
        waitDialog = new WaitDialog(AddTagTosActivity.this, R.style.updateDialog, "处理中,请稍后...");
        type_from = getIntent().getIntExtra("TYPE_FROM", -1);
        single_page = getIntent().getIntExtra("SINGLE_PAGE",0);
        sexuality = getIntent().getIntExtra(INTENT_KEY_SEXUALITY, 1);
        TAG_SIZE = getIntent().getIntExtra("SIZE", 5);
        themeKey = getIntent().getStringExtra(INTENT_KEY_THEME_KEY);
        mhandler = new Handler()
        {
            public void handleMessage(Message msg)
            {
                String tagString = msg.getData().get("tagString").toString();
                switch (msg.what)
                {
                    case MESSAGE_TAG_CLICK:
                    case MESSAGE_TAG_DELTE:
                        tempTagsList.remove(tagString);
                        tags_viewgroup.removeAllViews();
                        initUserTags();
                        tags_num_tv.setText("已添加标签数：" + tempTagsList.size() + "/" + TAG_SIZE);
                        break;
                    default:
                        break;
                }
            }
        };
        findId();
        initDate();
    }


    private void initAllTags()
    {
        initUserTags();
        tags_num_tv.setText("已添加标签数：" + tempTagsList.size() + "/" + TAG_SIZE);
    }

    private void initUserTags()
    {
        for (int i = 0; i < tempTagsList.size(); i++)
        {
            tags_viewgroup.addDoufuTagViewForTag(AddTagTosActivity.this, tempTagsList.get(i).trim().replace(" ", ""));
        }
    }



    private void initDate()
    {
        // TODO Auto-generated method stub
        tempTagsList.addAll((ArrayList<String>) getIntent().getSerializableExtra("existTagsList"));
        initAllTags();
        searchTAGAdapter = new TagAapater(AddTagTosActivity.this, hotTagsList);
        tags_list.setAdapter(searchTAGAdapter);
        loadData();
    }


    private void loadData()
    {
        // TODO Auto-generated method stub
        waitDialog.show();

        //加载推荐标签
        ApiClient.getInstance().setUseCache(true).getService().getRecommendTags(sexuality,themeKey,single_page)
                .compose(RxJavaHelper.<TagRecommendGsonBean>observeOnMainThread(this))
                .subscribe(new BaseSubscriber<TagRecommendGsonBean>(){
                    @Override
                    public void onNext(TagRecommendGsonBean tagRecommendGsonBean) {
                        super.onNext(tagRecommendGsonBean);
                        disimissDialog();
                        if (tagRecommendGsonBean != null) {
                            if (tagRecommendGsonBean.getData() != null) {
                                if (tagRecommendGsonBean.getData().getList() != null) {
                                    List<String> mainList = tagRecommendGsonBean.getData().getList();
                                    initHotData(mainList);
                                    searchTAGAdapter.notifyDataSetChanged();
                                }
                                if (!TextUtils.isEmpty(tagRecommendGsonBean.getData().getTip())){
                                    tvTip.setVisibility(View.VISIBLE);
                                    tvTip.setText(tagRecommendGsonBean.getData().getTip());
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        disimissDialog();
                    }
                });

    }


    private void disimissDialog() {
        if (waitDialog != null && waitDialog.isShowing()) {
            waitDialog.dismiss();
        }
    }

    private void findId()
    {
        // TODO Auto-generated method stub
        tvMakeSure = (TextView) findViewById(R.id.tvMakeSure);
        tvTip = (TextView) findViewById(R.id.tvTip);
        new_tag_ly =  findViewById(R.id.new_tag_ly);
        new_tag_tv = (TextView) findViewById(R.id.new_tag_tv);
        search_del =  findViewById(R.id.search_del);
        tipLayout = (LinearLayout) findViewById(R.id.personal_center_fans_tip);
        tags_viewgroup = (TextTagsViewGroup) findViewById(R.id.tags_viewgroup);
        tags_num_tv = (TextView) findViewById(R.id.tags_num_tv);
        search_tag_et = (EditText) findViewById(R.id.search_tag_et);
        tags_list = (GridView) findViewById(R.id.tags_list);

        hot_ly =  findViewById(R.id.hot_ly);
        latest_ly =  findViewById(R.id.latest_ly);
        search_ly =  findViewById(R.id.search_ly);
        hot_gv = (GridView) findViewById(R.id.hot_gv);
        latest_gv = (GridView) findViewById(R.id.latest_gv);
        ivBack = (ImageView) findViewById(R.id.ivBack);
        ivBack.setOnClickListener(this);
        tvMakeSure.setOnClickListener(this);
        new_tag_ly.setOnClickListener(this);
        latest_ly.setOnClickListener(this);
        search_del.setOnClickListener(this);
        hot_gv.setOnItemClickListener(new MyOnItemClickListner(1));
        tags_list.setOnItemClickListener(new MyOnItemClickListner(2));
        latest_gv.setOnItemClickListener(new MyOnItemClickListner(3));
        tags_viewgroup.addClickListenner(new MyClickListenner(mhandler));
        search_tag_et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (search_tag_et.getText().toString().trim().length() > 0) {
                    search_del.setVisibility(View.VISIBLE);
                    searchTAG(search_tag_et.getText().toString().trim());
                } else {
                    new_tag_ly.setVisibility(View.GONE);
                    search_del.setVisibility(View.GONE);
                    searchTAGAdapter.setData(hotTagsList);
                    if (searchTAGAdapter.getCount() == 0) {
                        tipLayout.setVisibility(View.VISIBLE);
                    } else {
                        tipLayout.setVisibility(View.INVISIBLE);
                    }
                }
                searchTAGAdapter.notifyDataSetChanged();
            }
        });

    }


    private void searchTAG(String tag)
    {
        last = "";
        UGCMainService.getInstance().getSearchTags(tag, last, AddTagTosActivity.this);
    }


    protected void filterTags() {
        // TODO Auto-generated method stub
        String name = search_tag_et.getText().toString().trim();
        if (name != null && !name.equals("")) {
            if (!searchTagsList.contains(name.trim())) {
                new_tag_ly.setVisibility(View.VISIBLE);
                new_tag_tv.setText(name);
            } else {
                new_tag_ly.setVisibility(View.GONE);
            }
            searchTAGAdapter.setData(searchTagsList);
        }
    }

    private boolean tagNotExist(String tagString) {
        for (int k = 0; k < tempTagsList.size(); k++) {
            if (tagString.equals(tempTagsList.get(k).trim().replace(" ", ""))) {
                return false;
            }
        }
        return true;
    }

    public void saveTagsData() {
        SharedPreferences sharedPreferences = getSharedPreferences("tags_use_history", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        //  String newTagsString = "";
        Set<String> historySet = sharedPreferences.getStringSet("tags" + type_from, new HashSet<String>());
        for (int i = 0; i < tempTagsList.size(); i++) {
            if (!historySet.contains(tempTagsList.get(i).trim().replace(" ", ""))) {
                if (!tag_needList.contains(tempTagsList.get(i).trim().replace(" ", ""))){ //不存官方的标签
                    historySet.add(tempTagsList.get(i).trim().replace(" ", ""));
                }
            }
        }
        if (historySet.size() > 100){ //控制长度
            historySet.clear();
        }
        editor.putStringSet("tags" + type_from, historySet);
        editor.commit();

    }

    public ArrayList<String> getLocalTagsData() {
        SharedPreferences sharedPreferences = getSharedPreferences("tags_use_history", Activity.MODE_PRIVATE);
        Set<String> historySet = sharedPreferences.getStringSet("tags" + type_from, new HashSet<String>());
        if (historySet != null) {
            String[] arr = new String[historySet.size()];
            historySet.toArray(arr);//Set-->数组
            if (arr.length <= TAG_HISTORY_SIZE_USER) {
                for (int i = 0; i < arr.length; i++) {
                    latestTagsList.add(arr[i]);
                }
            } else {
                for (int i = 0; i < TAG_HISTORY_SIZE_USER; i++) {
                    latestTagsList.add(arr[arr.length - i - 1]);
                }
            }
        }
        return latestTagsList;

    }

    @Override
    public void handleResponse(int handleType, HttpResponseObject response) {
        // TODO Auto-generated method stub
        waitDialog.dismiss();
        try {
            switch (handleType) {
                case UGCMainService.HANDLE_TYPE_LOAD_SEARCH_TAG:  //标签搜索
                    searchTagsList.clear();
                    search_ly.setVisibility(View.VISIBLE);
                    hot_ly.setVisibility(View.INVISIBLE);
                    latest_ly.setVisibility(View.INVISIBLE);

                    if (response.getStatus() == Constant.STATUS_SUCCESS) {
                        final JSONObject jsonObject = (JSONObject) response.getData();
                        List<TagBean> mainList = DiaobaoUtil.json2list(TagBean.class, jsonObject.getJSONArray("tags"));
                        for (int i = 0; i < mainList.size(); i++) {
                            searchTagsList.add(mainList.get(i).getName());
                        }
                        filterTags();
                    } else {
                        UIUtil.toastMessage(AddTagTosActivity.this, DiaobaoUtil.getErrorTips(response));
                    }
                    if (searchTAGAdapter.getCount() == 0) {
                        tipLayout.setVisibility(View.VISIBLE);
                    } else {
                        tipLayout.setVisibility(View.INVISIBLE);
                    }
                    searchTAGAdapter.notifyDataSetChanged();
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void initHotData(List<String> mainList) {
        hotTagsList.addAll(getLocalTagsData());
        for (int i = 0; i < mainList.size(); i++) {
            if (!hotTagsList.contains(mainList.get(i))) {
                hotTagsList.add(mainList.get(i));
            }
        }
    }

    @Override
    public void onClick(View view) {
        // TODO Auto-generated method stub
        switch (view.getId()) {
            case R.id.tvMakeSure:
                backWithData();
                break;
            case R.id.search_del:
                search_tag_et.setText("");
                break;
            case R.id.ivBack:
                finish();
                break;
            case R.id.new_tag_ly:
                if (tempTagsList.size() < TAG_SIZE) {
                    String addString = new_tag_tv.getText().toString().trim();
                    if (isTagAvalible(addString)) {
                        if (tagNotExist(addString)) {
                            tempTagsList.add(addString.trim().replace(" ", ""));
                            tags_viewgroup.addDoufuTagViewForTag(AddTagTosActivity.this, addString.trim().replace(" ", ""));
                            tags_num_tv.setText("已添加标签数：" + tempTagsList.size() + "/" + TAG_SIZE);
                            search_tag_et.setText("");
                        } else {
                            Toast.makeText(AddTagTosActivity.this, "你已经添加过这个标签了噢！", Toast.LENGTH_SHORT).show();
                        }
                    }
                } else {
                    Toast.makeText(AddTagTosActivity.this, "最多只能添加" + TAG_SIZE + "个标签噢！", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }

    }

    ArrayList<String> tag_needList = new ArrayList<String>();

    @Override
    public void onBackPressed() {
        backWithData();
        super.onBackPressed();
    }

    @Override
    public void finish() {
        saveTagsData();
        super.finish();
    }

    private void backWithData() {
        Intent intent = new Intent();
        intent.putStringArrayListExtra("TAGS_LIST", tempTagsList);
        EventBusMyTag event = new EventBusMyTag();
        event.setTag(EventBusMyTag.tag);
        event.setList(tempTagsList);
        EventBus.getDefault().post(event);
        setResult(MESSAGE_TAG_BACK, intent);
        finish();
        //  }
    }



    private class MyOnItemClickListner implements AdapterView.OnItemClickListener {
        int type;

        public MyOnItemClickListner(int type)
        {
            this.type = type;
        }

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            String addString = "";

            if (tempTagsList.size() < TAG_SIZE) {
                switch (type) {
                    case 1:
                        addString = hotTagsList.get(position);
                        break;
                    case 2:
                        // addString = searchTagsList.get(position);
                        TextView textView = (TextView) view.findViewById(R.id.item_tag_title);
                        addString = textView.getText().toString();
                        break;
                    case 3:
                        addString = latestTagsList.get(position);
                        break;
                }
                if (isTagAvalible(addString)) {
                    if (tagNotExist(addString)) {
                        tempTagsList.add(addString.trim().replace(" ", ""));
                        tags_viewgroup.addDoufuTagViewForTag(AddTagTosActivity.this, addString.trim().replace(" ", ""));
                        tags_num_tv.setText("已添加标签数：" + tempTagsList.size() + "/" + TAG_SIZE);
                        search_tag_et.setText("");
                    } else {
                        Toast.makeText(AddTagTosActivity.this, "你已经添加过这个标签了噢！", Toast.LENGTH_SHORT).show();
                    }
                }
            } else {
                Toast.makeText(AddTagTosActivity.this, "最多只能添加" + TAG_SIZE + "个标签噢！", Toast.LENGTH_SHORT).show();
            }

        }
    }

    public boolean isTagAvalible(String inputStr) {
        if (inputStr != null && !inputStr.isEmpty() && inputStr.length() > 0) {
            if (inputStr.length() > TAG_MAX_SIZE) {
                UIUtil.toastMessage(AddTagTosActivity.this, "最多只能" + TAG_MAX_SIZE + "个字哦");
                return false;
            }
            if (!isTagsLegal(inputStr)) {
                return false;
            }
            return true;
        } else {
            UIUtil.toastMessage(AddTagTosActivity.this, "标签不能为空噢");
            return false;
        }
    }

    private boolean isTagsLegal(String str) {
        Pattern pattern = Pattern.compile("^[\u4E00-\u9FA5A-Za-z0-9]+$");
        Matcher m = pattern.matcher(str);
        if (m.find()) {
            return true;
        }
        UIUtil.toastMessage(AddTagTosActivity.this, "标签只能包含汉字、字母和数字");
        return false;
    }

    @Override
    protected void onResume() {
        MobclickAgent.onResume(this);
        super.onResume();
    }
}